<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :visible.sync="visible">
      <el-form v-loading="formLoading" :model="dataForm" inline :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
        <el-form-item label="所属基地" prop="deptId">
          <el-input v-model="dataForm.deptName" v-popover:deptListPopover readonly="true" placeholder="所属基地"></el-input>
          <!-- <el-tooltip class="item" style="width:10%;" effect="dark" content="更换基地将会清除田块" placement="top-start">
          <el-button>*</el-button> -->
         <!-- </el-tooltip> -->
            <el-popover ref="deptListPopover" placement="bottom-start" trigger="click" @hide="hidep()">
              <el-tree
                
                ref="deptListTree" node-key="id" 
                show-checkbox
                :data="deptList" 
                :props="deptListTreeProps"
                @check-change="checkChange"
                :check-strictly="true" 
                :default-expand-all="true"
                :highlight-current="true" 
                :expand-on-click-node="false"
              >
              </el-tree>
          </el-popover>
        </el-form-item>

        <el-form-item label="巡检田块" prop="bussFarmlandInfoIds">
          <div @click="changeInput">
            <el-input v-model="bussFarmlandInfoIdsname" readonly=""  placeholder="巡检田块"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="巡检人" prop="handler">
          <el-select class="form-item" v-model="dataForm.handler" filterable placeholder="巡检人">
            <el-option value="">请选择巡检人</el-option>
              <el-option
              v-for="item in tkList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="部门（基地）id" prop="deptId">
          <el-input v-model="dataForm.deptId" placeholder="部门（基地）id"></el-input>
        </el-form-item> -->

        <el-form-item label="巡检计划名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="巡检计划名称"></el-input>
        </el-form-item>
        <el-form-item label="频率" prop="frequencyFormula">
          <el-input-number v-if="fen" class="form-item" v-model="dataForm.frequencyFormula" :min="1" :max="60" label="频率（分）"></el-input-number>
          <el-input-number v-if="shi" class="form-item" v-model="dataForm.frequencyFormula" :min="1" :max="24" label="频率（时）"></el-input-number>
          <el-input-number v-if="tian" class="form-item" v-model="dataForm.frequencyFormula" :min="1" :max="30" label="频率（天）"></el-input-number>
          <el-input-number v-if="zhou" class="form-item" v-model="dataForm.frequencyFormula" :min="1" :max="30" label="频率（周）"></el-input-number>
          <el-select @change="plchange" class="form-item" v-model="dataForm.frequencyFormulatype"  placeholder="请选择">
             <el-option
              v-for="item in pl"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          
          <el-select class="form-item" v-model="dataForm.status"  placeholder="请选择状态">
                <el-option
              v-for="item in ztoption"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检内容" prop="content" >
          <el-input style="width:500px" type="textarea" :rows="3" v-model="dataForm.content" placeholder="巡检内容"></el-input>
        </el-form-item>

        
        <!-- <el-form-item label="启动时间" prop="startTime">
          <el-input v-model="dataForm.startTime" placeholder="启动时间"></el-input>
        </el-form-item>   -->
         <!-- <el-form-item  label="启动时间" prop="startTime">
          <el-date-picker
            class="form-item"
            v-model="dataForm.startTime"
            type="datetime"
            placeholder="启动时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            >
          </el-date-picker> -->
       
    <!-- </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button v-loading="formLoading" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    </el-dialog>
    
    <bussfarmlandinfoSelect v-if="bussfarmlandinfoSelectVisible" ref="bussfarmlandinfoSelect"
        @bussFarmlandInfoSelectChange="bussFarmlandInfoSelectChange"></bussfarmlandinfoSelect>
  </div>
</template>

<script>
 import { treeDataTranslate } from '@/utils'
 import bussfarmlandinfoSelect from './bussfarmlandinfoSelect'
  export default {
    data () {
      return {
        visible: false,
        formLoading: false,
        demoVisible: false,
        reportLayer:false,
        bussfarmlandinfoSelectVisible:false,
        dataForm: {
          id: 0,
          bussFarmlandInfoIds: '',
          handler: '',
          deptId: '',
          deptName:'',
          name: '',
          content: '',
          status: '',
          frequencyFormula: '',
          frequencyFormulatype:'',
          startTime: '',
        },
        ztoption: [{
          value: Number('0'),
          label: '启用'
        }, {
          value: Number('1'),
          label: ' 禁用'
        }],
        pl: [{
          value: '周',
          label: '周'
        }, {
          value: '天',
          label: '天'
        }, {
          value: '时',
          label: '时'
        }, {
          value: '分',
          label: '分'
        }],
        bussFarmlandInfoIdsname:'',
        dataRule: {
          bussFarmlandInfoIds: [
            { required: true, message: '巡检田块不能为空', trigger: 'change' }
          ],
          handler: [
            { required: true, message: '巡检人不能为空', trigger: 'blur' }
          ],
          deptId: [
            { required: true, message: '基地不能为空', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '巡检计划名称不能为空', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '巡检内容不能为空', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '状态不能为空', trigger: 'blur' }
          ],
          frequencyFormula: [
            { required: true, message: '频率不能为空', trigger: 'blur' }
          ],
         

        },
          menuList: [],
        multipleSelection: [],
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        key: '',
         menuListTreeProps: {
          label: 'name',
          children: 'children'
        },
         deptList: [],
        deptListTreeProps: {
          label: 'name',
          children: 'children',
          disabled: function(data, node){
            return data.type == 1 ? false :true
          }
        },
        tkList:[],// 田块列表
        fen:false,
        shi:false,
        tian:false,
        zhou:false,
        oldvalue:'',
      }
    },
    components: {
      bussfarmlandinfoSelect
    },
    methods: {
     init (id) {
        this.dataForm.deptId = ''
        this.dataForm.deptName = ''

        this.getTkList();
        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/dept/select2'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.deptList = treeDataTranslate(data.deptList, 'id')
        }).then(() => {
          this.visible = true
          this.formLoading = false
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
            })
          }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/buss/bussinspectionplan/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.bussFarmlandInfoIds = data.bussInspectionPlan.bussFarmlandInfoIds
                this.dataForm.handler = data.bussInspectionPlan.handler
                this.dataForm.deptId = data.bussInspectionPlan.deptId
                this.dataForm.name = data.bussInspectionPlan.name
                this.dataForm.content = data.bussInspectionPlan.content
                this.dataForm.status = data.bussInspectionPlan.status
                this.dataForm.frequencyFormula = data.bussInspectionPlan.frequencyFormula
                this.dataForm.frequencyFormulatype = data.bussInspectionPlan.frequencyFormulatype
                this.dataForm.startTime = data.bussInspectionPlan.startTime
                this.dataForm.version = data.bussInspectionPlan.version
                this.bussFarmlandInfoIdsname = data.bussInspectionPlan.tkNames
                this.oldvalue = data.bussInspectionPlan.deptId
                if(data.bussInspectionPlan.frequencyFormulatype == '分'){
                   this.fen = true
                }else if(data.bussInspectionPlan.frequencyFormulatype == '时'){
                   this.shi = true
                }else if(data.bussInspectionPlan.frequencyFormulatype == '天'){
                  this.tian = true
                }else if(data.bussInspectionPlan.frequencyFormulatype == '周'){
                  this.zhou = true
                }
                this.deptListTreeSetCurrentNode()
                // data.bussInspectionPlan.bussFarmlandInfoIds
            
                //  this.multipleSelection = 
                
              }
            })
          }
        })
      },
     plchange(){
        //  console.log(this.dataForm.frequencyFormulatype);
        if(this.dataForm.frequencyFormulatype == '周'){
           this.fen = false
           this.shi = false
           this.tian = false
           this.zhou = true
        }else if(this.dataForm.frequencyFormulatype == '天'){
          this.fen = false
           this.shi = false
           this.tian = true
           this.zhou = false

        }else if(this.dataForm.frequencyFormulatype == '时'){
          this.fen = false
           this.shi = true
           this.tian = false
           this.zhou = false

        }else if(this.dataForm.frequencyFormulatype == '分'){
          this.fen = false
           this.shi = true
           this.tian = false
           this.zhou = false

        }

     },
     hidep () {
        if(this.dataForm.deptId == ''){
          //this.oldvalue = this.dataForm.deptId
        }else
        if( this.oldvalue != this.dataForm.deptId && this.oldvalue != ''){

          this.$confirm('更换基地将清除田块')
            .then(_ => {
              this.dataForm.bussFarmlandInfoIds = ''
              this.bussFarmlandInfoIdsname = ''
              this.oldvalue = this.dataForm.deptId
               this.checki()
          })
          .catch(_ => {
            this.dataForm.deptId  = this.oldvalue
              this.checki()

          });
          } else if(this.oldvalue == ''){
             this.dataForm.bussFarmlandInfoIds = ''
              this.bussFarmlandInfoIdsname = ''
              this.oldvalue = this.dataForm.deptId
               this.checki()
            
          } 
      },
       checki(){
        this.checkedId = this.dataForm.deptId;
        var b = this.$refs.deptListTree.getCheckedNodes(this.checkedId)
        this.$refs.deptListTree.setCheckedNodes([b])
        this.deptListTreeSetCurrentNode();
      },
      // 菜单树设置当前选中节点
      deptListTreeSetCurrentNode () {
        debugger;
        this.$refs.deptListTree.setChecked(this.dataForm.deptId,true,false)
        this.dataForm.deptName = (this.$refs.deptListTree.getCheckedNodes() || [])[0].name
      },
      // 节点修改
      checkChange(data, checked, node){
        debugger
          if(checked == true){// 选中部门
          //  this.dataForm.farmlandInfoIds = ''
          //  this.farmlandInfoIdsname = ''
            this.checkedId = data.id;
            this.$refs.deptListTree.setCheckedNodes([data])
            this.dataForm.deptId = data.id
            this.dataForm.deptName = data.name
          }
      },
      // 表单提交
      dataFormSubmit () {
        console.log(this.dataForm);
        this.$refs['dataForm'].validate((valid) => {
          if (valid && !this.formLoading) {
            this.formLoading = true
            this.$http({
              url: this.$http.adornUrl(`/buss/bussinspectionplan/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'bussFarmlandInfoIds': this.dataForm.bussFarmlandInfoIds,
                'handler': this.dataForm.handler,
                'deptId': this.dataForm.deptId,
                'name': this.dataForm.name,
                'content': this.dataForm.content,
                'status': this.dataForm.status,
                'frequencyFormula': this.dataForm.frequencyFormula,
                'startTime': this.dataForm.startTime,
                'frequencyFormulatype':this.dataForm.frequencyFormulatype,
                'version':this.dataForm.version,

              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.formLoading = false
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 点击输入框选择田块
      changeInput() {
        // this.demoVisible = true
        // if (this.multipleSelection.length == 0) {
        //   this.search()
        // }
        if(this.dataForm.deptId==null||this.dataForm.deptId==''||this.dataForm.deptId==undefined){
          alert('请先选择基地！！！');
          return
        }
        this.bussfarmlandinfoSelectVisible =true
        this.$nextTick(() => {
          this.$refs.bussfarmlandinfoSelect.init(this.dataForm.bussFarmlandInfoIds,this.dataForm.deptId)
        })
      },
      // 田块选择回调方法
      bussFarmlandInfoSelectChange(ids,names){
        
          this.dataForm.bussFarmlandInfoIds = ids
          this.bussFarmlandInfoIdsname = names
      },
       getTkList(){
          this.$http({
            url: this.$http.adornUrl('/sys/user/list2'),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
             this.tkList = data.page.list
          })    	     	       	
      },
    }
  }
</script>

<style scoped>
  .el-row {
    margin: 5px 0;
  }
</style>
